import list from "./list";

class City {
  getProvince() {
    let provinces = {};
    let old = "000000";
    let oldProvince = "00";
    let oldCity = "0000";
    // 遍历格式化城市数据
    Object.keys(list).forEach(k => {
      // 获取所有省、自治区、直辖市
      if (old.substring(0, 2) !== k.substring(0, 2)) {
        // 初始化省对象
        if (provinces[k] === undefined) {
          provinces[k] = {};
        }
        // 设置省名称
        provinces[k]["province"] = list[k];
        // 存放当前省id
        oldProvince = k;
        // 对直辖市和特别行政区做特别处理
        if (
          list[k].substring(list[k].length - 1, list[k].length) === "市" ||
          (list[k].length === 7 &&
            list[k].substring(2, list[k].length) === "特别行政区")
        ) {
          provinces[oldProvince]["citys"] = {};
          provinces[oldProvince]["citys"][k] = {};
          provinces[oldProvince]["citys"][k]["city"] = list[k];
          oldCity = k;
        }
      }
      // 获取所有省下的市，过滤直辖市和特别行政区做特别处理
      else if (
        old.substring(0, 4) !== k.substring(0, 4) &&
        k.substring(4, 6) === "00"
      ) {
        // 初始化市对象集合
        if (provinces[oldProvince]["citys"] === undefined) {
          provinces[oldProvince]["citys"] = {};
        }
        // 初始化市对象
        if (provinces[oldProvince]["citys"][k] === undefined) {
          provinces[oldProvince]["citys"][k] = {};
        }
        // 给市对象赋值
        provinces[oldProvince]["citys"][k]["city"] = list[k];
        // 存放当前市id
        oldCity = k;
      }
      // 获取所有市下的县、区
      else if (old !== k) {
        // 初始化区集合
        if (provinces[oldProvince]["citys"][oldCity]["countys"] === undefined) {
          provinces[oldProvince]["citys"][oldCity]["countys"] = {};
        }
        // 给区对象赋值
        provinces[oldProvince]["citys"][oldCity]["countys"][k] = list[k];
      }
      // 存放当前遍历对象
      old = k;
    });
    return provinces;
  }
  getAddress(pid, cid, cuid) {
    let provinces = this.getProvince();
    let provunce = provinces[pid];
    let city = provunce.citys[cid];
    let county = city.countys[cuid];
    return provunce.province + " " + city.city + " " + county;
  }
}

export default City;
